<template>
  <section class="component filing-step">
    <el-form :model="formData" :rules="needErrorMsg? rules:{}" ref="filing-step-form" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="处理方式：" prop="treatmentType">
            <el-select :disabled="isDetail" v-model="formData.treatmentType">
              <el-option v-for="{index,name,code} in $dict.getDictData('TreatmentType')" :key="index" :label="name" :value="code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="原告信息：" prop="plaintiffInfo">
            <!-- 2021-06-16-原告信息由下拉选择框改为input输入框 -->
            <!-- <el-select v-model="formData.plaintiffInfo">
              <el-option v-for="{index,name,code} in $dict.getDictData('PlaintiffInformation')" :key="index" :label="name" :value="code">
              </el-option>
            </el-select> -->
            <el-input :disabled="isDetail" v-model="formData.plaintiffInfo" maxlength="100"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="被告人姓名：" prop="defendantName">
            <el-input :disabled="isDetail" v-model="formData.defendantName" maxlength="10"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号：" prop="defendantNameId">
            <el-input :disabled="isDetail" v-model="formData.defendantNameId" maxlength="18"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法院/仲裁委：" prop="court">
            <el-input :disabled="isDetail" v-model="formData.court" maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="案号：" prop="legalCaseNum">
            <el-input :disabled="isDetail" v-model="formData.legalCaseNum" maxlength="20"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否保全：" prop="isPreserve">
            <el-select :disabled="isDetail" v-model="formData.isPreserve">
              <el-option v-for="{index,name,code} in $dict.getDictData('CommonFlag')" :key="index" :label="name" :value="code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="保全金额：" prop="preserveMoney">
            <el-input :disabled="isDetail" v-model="formData.preserveMoney" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="诉讼/保全费：" prop="legalMoney">
            <el-input :disabled="isDetail" v-model="formData.legalMoney" type="number"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公告费：" prop="noticeMoney">
            <el-input :disabled="isDetail" v-model="formData.noticeMoney" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="案件归属人：" prop="caseBelonger">
        <el-input v-model="formData.caseBelonger" disabled></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法务档案编号：" prop="legalArchiveNo">
            <el-input :disabled="isDetail" v-model="formData.legalArchiveNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法务档案存放地：" prop="legalArchiveAddr">
            <el-input :disabled="isDetail" v-model="formData.legalArchiveAddr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法务案卷编号：" prop="legalRecordNo">
            <el-input :disabled="isDetail" v-model="formData.legalRecordNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法务案卷存放地：" prop="legalRecordAddr">
            <el-input :disabled="isDetail" v-model="formData.legalRecordAddr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="立案备注：" prop="registerRemark">
        <el-input :disabled="isDetail" type="textarea" v-model="formData.registerRemark" maxlength="200" show-word-limit></el-input>
      </el-form-item>
    </el-form>
    <div class="text-center">
      <el-button v-if="isShow" @click="submit" :loading="submitLoading">保存</el-button>
      <el-button @click="nextStepEmit">下一步</el-button>
      <el-button @click="finishCaseEmit">结案</el-button>
    </div>
  </section>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Prop, Emit, Watch, Provide } from "vue-property-decorator";
import { Dependencies } from '~/core/decorator';
import { CaseOperatorPageService } from '~/services/domain-service/case-operator-page.service';
import { CaseLegalRecordService } from '~/services/domain-service/case-legalRecord.service';
import { State, Action, Getter, namespace } from "vuex-class";
import { MENU_CHANNEL } from "~/config/enum.config";
const CollectionExecutionModule = namespace('collection-execution');
@Component({
  components: {}
})

export default class FilingStep extends Vue {
  @Dependencies(CaseOperatorPageService) private caseOperatorPageService: CaseOperatorPageService;
  @Dependencies(CaseLegalRecordService) private caseLegalRecordService: CaseLegalRecordService;
  @CollectionExecutionModule.State private caseId;
  @CollectionExecutionModule.State private menuChannel;
  @CollectionExecutionModule.State private otherData;
  @CollectionExecutionModule.Mutation private updateCurrentSavedStep;

  @Prop({ type: String, required: false }) private id;
  @Prop() private topInfo
  @Prop({ type: String }) private operatorId
  @Prop({ type: Boolean }) private isDetail
  @State private userData: any;
  @Prop({ type: Boolean }) private needErrorMsg

  private formData: any = {
    legalStage: "REGISTER",
    id: "",
    treatmentType: "LITIGATION",
    plaintiffInfo: "",
    defendantName: "",
    defendantNameId: "",
    court: "",
    legalCaseNum: "",
    isPreserve: "YES",
    preserveMoney: "",
    legalMoney: "",
    noticeMoney: "",
    caseBelonger: "",
    legalArchiveNo: "",
    legalArchiveAddr: "",
    legalRecordNo: "",
    legalRecordAddr: "",
    registerRemark: "",
    caseInfoRecordId: ""
  }
  //数据校验
  private rules: any = {
    treatmentType: [{ required: true, message: "请选择处理方式" }],
    plaintiffInfo: [{ required: true, message: "请输入原告信息" }],
    defendantName: [{ required: true, message: "请输入被告人姓名", trigger: "blur" }],
    defendantNameId: [{ required: true, message: "请输入身份证号", trigger: "blur" }],
    court: [{ required: true, message: "请输入法院/仲裁委" }],
    legalCaseNum: [{ required: true, message: "请输入案号" }],
    isPreserve: [{ required: true, message: "请选择是否保全" }],
  };
  private submitLoading: boolean = false

  private get isShow () {
    console.log('operatorId', this.operatorId);
    const arr = [MENU_CHANNEL.Legal_personal, MENU_CHANNEL.Legal_team, MENU_CHANNEL.Assist_legal, MENU_CHANNEL.Assist_legal]
    if (arr.find(v => this.menuChannel === v)) {
      // 添加催记显示保存按钮 或编辑催记 与该登录用户一致显示
      if (!this.operatorId || this.operatorId === this.userData.id) return true
      else return false
    }
    return false
  }



  @Emit('nextStep')
  private nextStepEmit () {
    const form: any = this.$refs["filing-step-form"];
    form.validate(valid => {
      if (!valid) return false;
    })
  }

  @Emit('finishCase')
  private finishCaseEmit () { }

  @Emit('emitSuccess')
  private emitSuccess () {
    if (this.id) {
      this.showLegalInfoById(this.id);
    } else {
      // this.showLegalInfo();
    }
  }

  @Watch('topInfo')
  private showPersonalName (val) {
    if (this.caseId && !this.id) {
      console.log('watch topInfo', this.topInfo);
      this.formData.defendantName = val.personalName;
      // this.formData.defendantNameId = val.personalId;
      this.formData.defendantNameId = val.idCard;
    }
  }

  private showLegalInfoById (val) {
    console.log("val", val)
    const vals = { "caseLegalRecordId": val }
    // 列表详情
    this.caseLegalRecordService
      .getCaseLegalRecordById(vals)
      .subscribe(
        (data) => {
          console.log('data', data);

          if (data) {
            this.formData.id = data.id;
            this.formData.treatmentType = data.treatmentType;
            this.formData.plaintiffInfo = data.plaintiffInfo;
            if (data.isRegister === "YES") {
              this.formData.defendantName = data.defendantName;
              this.formData.defendantNameId = data.defendantNameId;
              this.formData.court = data.court;
            }
            this.formData.legalCaseNum = data.legalCaseNum;
            this.formData.isPreserve = data.isPreserve;
            this.formData.preserveMoney = data.preserveMoney;
            this.formData.legalMoney = data.legalMoney;
            this.formData.noticeMoney = data.noticeMoney;
            this.formData.caseBelonger = data.caseBelonger;
            this.formData.legalArchiveNo = data.legalArchiveNo;
            this.formData.legalArchiveAddr = data.legalArchiveAddr;
            this.formData.legalRecordNo = data.legalRecordNo;
            this.formData.legalRecordAddr = data.legalRecordAddr;
            this.formData.registerRemark = data.registerRemark;
          }
        },
        (err) => {

        },
      );
  }

  private mounted () {

    if (this.id) {
      console.log('？');
      this.showLegalInfoById(this.id)
    } else {
      console.log('topinfo', this.topInfo);
      console.log('this.formData', this.formData);

      // this.formData.defendantNameId = this.topInfo.personalId;
      this.formData.defendantNameId = this.topInfo.idCard;
      this.formData.defendantName = this.topInfo.personalName;
      this.formData.caseBelonger = this.userData.realName;

      // this.showLegalInfo();
    }
  }

  private showLegalInfo () {
    //查询上一条催记是否结案，回显数据
    this.caseOperatorPageService
      .queryUnClossCaseLegalRecord(this.caseId)
      .subscribe(
        (data) => {
          if (data) {
            this.formData.id = data.id;
            this.formData.treatmentType = data.treatmentType;
            this.formData.plaintiffInfo = data.plaintiffInfo;
            if (data.isRegister === "YES") {
              this.formData.defendantName = data.defendantName;
              this.formData.defendantNameId = data.defendantNameId;
              this.formData.court = data.court;
              this.formData.caseBelonger = data.caseBelonger;
            }
            this.formData.legalCaseNum = data.legalCaseNum;
            this.formData.isPreserve = data.isPreserve;
            this.formData.preserveMoney = data.preserveMoney;
            this.formData.legalMoney = data.legalMoney;
            this.formData.noticeMoney = data.noticeMoney;
            this.formData.legalArchiveNo = data.legalArchiveNo;
            this.formData.legalArchiveAddr = data.legalArchiveAddr;
            this.formData.legalRecordNo = data.legalRecordNo;
            this.formData.legalRecordAddr = data.legalRecordAddr;
            this.formData.registerRemark = data.registerRemark;
          }
        },
        (err) => { },
      );
  }

  private setCurrentFormDataVal (step) {
    this.updateCurrentSavedStep(step)
    sessionStorage.setItem('currentFormDataVal', JSON.stringify(this.formData))
    setTimeout(() => {
      const formData = JSON.parse(sessionStorage.getItem('currentFormDataVal') || "") || {}

      // this.formData = formData
      this.toInitData(formData)
    }, 300);
  }

  private toInitData (data) {
    const  formData = { ...data }

    for (const key in this.formData) {
      if (!['treatmentType', 'defendantName', 'defendantNameId', 'isPreserve','caseBelonger'].includes(key)) {
        formData[key] = ''
      }
    }

    this.formData = formData

  }

  private submit () {
    const form: any = this.$refs["filing-step-form"];
    form.validate(valid => {
      if (!valid) return false;
      if (this.menuChannel === MENU_CHANNEL.Assist_legal) {
        this.formData.assistId = this.otherData.assistId;
      }
      this.formData.caseId = this.caseId;
      // this.formData.caseLegalRecordId = this.caseId;
      // this.formData.caseInfoRecordId = this.caseId;
      if (this.caseId && this.id) {
        this.setCurrentFormDataVal(0)
        this.caseLegalRecordService.editCaseLegalRecord(this.formData).subscribe(
          (data) => {
            form.resetFields();
            this.emitSuccess();
            this.$message.success('法催催记立案已修改成功');
            // this.toInitData()

          },
          (err) => {
            this.submitLoading = false;
          },
        );
      } else {
        this.setCurrentFormDataVal(0)
        this.caseLegalRecordService.addCaseLegalRecord(this.formData).subscribe(
          (data) => {
            form.resetFields();
            this.emitSuccess();
            // this.toInitData()
            this.$message.success('法催催记立案已添加成功，如需修改请在法务详情中进行修改');
          },
          (err) => {
            this.submitLoading = false;
          },
        );
      }
    });
  }
}

</script>